"""
配置管理器
负责从数据库加载配置，为数据清洗处理器提供配置数据
"""
import re
import logging
from typing import List, Dict, Set, Optional
from sqlalchemy.orm import Session

from backend.data_clean.models import (
    BrandConfig, CommonProductName, UnitConfig, 
    MarketingWordConfig, SystemConfig
)

# 设置日志
logger = logging.getLogger(__name__)

class ConfigManager:
    """配置管理器"""
    
    def __init__(self):
        self._brands: List[str] = []
        self._brand_dict: Dict[str, Dict] = {}
        self._common_products: List[str] = []
        self._common_product_dict: Dict[str, Dict] = {}
        self._units: List[str] = []
        self._unit_dict: Dict[str, Dict] = {}
        self._marketing_words: List[str] = []
        self._marketing_word_dict: Dict[str, Dict] = {}
        self._system_config: Dict[str, str] = {}
        
        # 默认配置
        self._specification_pattern = r'\d+\.?\d*\s*(?:{units})'
        self._brand_char_range = r'[\u4e00-\u9fa5]'
        self._brand_max_length = 3
        
        self._is_initialized = False
    
    def initialize(self, db: Session):
        """从数据库初始化配置"""
        self._load_brands(db)
        self._load_common_products(db)
        self._load_units(db)
        self._load_marketing_words(db)
        self._load_system_config(db)
        self._is_initialized = True
        logger.info("配置管理器初始化完成")
    
    def _load_brands(self, db: Session):
        """加载品牌配置"""
        try:
            brand_configs = db.query(BrandConfig).filter(BrandConfig.is_active == True).all()
            self._brands = [brand.name for brand in brand_configs]
            self._brand_dict = {brand.name: {
                "id": brand.id,
                "category": brand.category,
                "is_active": brand.is_active
            } for brand in brand_configs}
            logger.info(f"加载了 {len(self._brands)} 个品牌配置")
        except Exception as e:
            logger.error(f"加载品牌配置失败: {str(e)}")
            # 使用默认的空列表
    
    def _load_common_products(self, db: Session):
        """加载商品名称排除列表"""
        try:
            product_configs = db.query(CommonProductName).filter(CommonProductName.is_active == True).all()
            self._common_products = [product.name for product in product_configs]
            self._common_product_dict = {product.name: {
                "id": product.id,
                "category": product.category,
                "description": product.description,
                "is_active": product.is_active
            } for product in product_configs}
            logger.info(f"加载了 {len(self._common_products)} 个商品名称排除项")
        except Exception as e:
            logger.error(f"加载商品名称排除列表失败: {str(e)}")
            # 使用默认的空列表
    
    def _load_units(self, db: Session):
        """加载单位配置"""
        try:
            unit_configs = db.query(UnitConfig).filter(UnitConfig.is_active == True).all()
            self._units = [unit.name for unit in unit_configs]
            self._unit_dict = {unit.name: {
                "id": unit.id,
                "type": unit.type,
                "is_active": unit.is_active
            } for unit in unit_configs}
            logger.info(f"加载了 {len(self._units)} 个单位配置")
        except Exception as e:
            logger.error(f"加载单位配置失败: {str(e)}")
            # 使用默认的空列表
    
    def _load_marketing_words(self, db: Session):
        """加载营销词配置"""
        try:
            word_configs = db.query(MarketingWordConfig).filter(MarketingWordConfig.is_active == True).all()
            self._marketing_words = [word.word for word in word_configs]
            self._marketing_word_dict = {word.word: {
                "id": word.id,
                "category": word.category,
                "is_active": word.is_active
            } for word in word_configs}
            logger.info(f"加载了 {len(self._marketing_words)} 个营销词配置")
        except Exception as e:
            logger.error(f"加载营销词配置失败: {str(e)}")
            # 使用默认的空列表
    
    def _load_system_config(self, db: Session):
        """加载系统配置"""
        try:
            system_configs = db.query(SystemConfig).all()
            self._system_config = {config.key: config.value for config in system_configs}
            
            # 设置规格匹配模式
            if "SPECIFICATION_PATTERN" in self._system_config:
                self._specification_pattern = self._system_config["SPECIFICATION_PATTERN"]
            
            # 设置品牌字符范围
            if "BRAND_CHAR_RANGE" in self._system_config:
                self._brand_char_range = self._system_config["BRAND_CHAR_RANGE"]
            
            # 设置品牌最大长度
            if "BRAND_MAX_LENGTH" in self._system_config:
                try:
                    self._brand_max_length = int(self._system_config["BRAND_MAX_LENGTH"])
                except (ValueError, TypeError):
                    logger.warning("品牌最大长度解析失败，使用默认值3")
            
            logger.info(f"加载了 {len(self._system_config)} 个系统配置")
        except Exception as e:
            logger.error(f"加载系统配置失败: {str(e)}")
            # 使用默认配置
    
    def reload(self, db: Session):
        """重新加载配置"""
        self.initialize(db)
    
    @property
    def brands(self) -> List[str]:
        """获取品牌列表"""
        return self._brands
    
    @property
    def brand_dict(self) -> Dict[str, Dict]:
        """获取品牌字典"""
        return self._brand_dict
    
    def is_brand(self, name: str) -> bool:
        """检查是否是品牌"""
        return name in self._brands
    
    @property
    def common_products(self) -> List[str]:
        """获取商品名称排除列表"""
        return self._common_products
    
    @property
    def common_product_dict(self) -> Dict[str, Dict]:
        """获取商品名称排除字典"""
        return self._common_product_dict
    
    def is_common_product(self, name: str) -> bool:
        """检查是否是常见商品名称"""
        return name in self._common_products
    
    @property
    def units(self) -> List[str]:
        """获取单位列表"""
        return self._units
    
    @property
    def unit_dict(self) -> Dict[str, Dict]:
        """获取单位字典"""
        return self._unit_dict
    
    def is_unit(self, name: str) -> bool:
        """检查是否是单位"""
        return name in self._units
    
    @property
    def marketing_words(self) -> List[str]:
        """获取营销词列表"""
        return self._marketing_words
    
    @property
    def marketing_word_dict(self) -> Dict[str, Dict]:
        """获取营销词字典"""
        return self._marketing_word_dict
    
    def is_marketing_word(self, word: str) -> bool:
        """检查是否是营销词"""
        return word in self._marketing_words
    
    @property
    def specification_pattern(self) -> str:
        """获取规格匹配模式"""
        return self._specification_pattern
    
    @property
    def brand_char_range(self) -> str:
        """获取品牌字符范围"""
        return self._brand_char_range
    
    @property
    def brand_max_length(self) -> int:
        """获取品牌最大长度"""
        return self._brand_max_length
    
    def get_brand_pattern(self) -> str:
        """获取品牌匹配模式"""
        return f'^{self._brand_char_range}{{2,{self._brand_max_length}}}'
    
    def get_specification_pattern_with_units(self) -> str:
        """获取带单位的规格匹配模式"""
        if not self._units:
            return r'\d+\.?\d*\s*(?:个|件|包|袋|箱|瓶|罐|盒|片|克|g|kg|千克|升|ml|L)'
        
        return self._specification_pattern.format(units='|'.join(self._units))
    
    def get_unknown_brand(self, brand: str) -> Dict:
        """获取未知品牌信息"""
        return {
            "id": None,
            "name": brand,
            "category": "未知",
            "is_in_database": False
        }
    
    def get_brand_info(self, brand: str) -> Dict:
        """获取品牌信息"""
        if brand in self._brand_dict:
            return {
                "id": self._brand_dict[brand]["id"],
                "name": brand,
                "category": self._brand_dict[brand]["category"],
                "is_in_database": True
            }
        return self.get_unknown_brand(brand)

# 创建全局配置管理器实例
config_manager = ConfigManager() 